<script setup lang='ts'>
	import type { pageInfo } from '@/api/type'
	import {ref} from 'vue'
	import { statusBarHeight } from '@/utils/system'
	import {onLoad, onShareAppMessage, onShareTimeline} from '@dcloudio/uni-app'
	import { setupScoreAPI, writeDownLoadAPI, detailWallAPI } from '../../api/api'
	// 切换蒙层显示与隐藏
	const modelState = ref(true)
	function modelChange() {
		modelState.value = !modelState.value
	}
	
	// 信息底部弹窗
	const popupInfo = ref(null)
	function clickInfo() {
		popupInfo.value.open()
	}
	
	function popupClose() {
		// console.log(popupInfo.value);
		popupInfo.value.close()
	}
	
	// 评分弹窗
	const popupScore = ref(null)
	// 判断是否评分过
	const isScore = ref(false)
	function clickscore() {
		if (pageInfo.value.userScore) {
			isScore.value = true
			userScore.value = pageInfo.value.userScore
		}
		popupScore.value.open()
	}
	// 评分
	const userScore = ref(0)
	// 评分关闭
	function popupScoreClose() {
		popupScore.value.close()
		// 重置评分
		userScore.value = 0
		isScore.value = false
	}
	
	// 确认评分
	async function submitScore() {
		uni.showLoading({
			title: '加载中'
		})
		const res = await setupScoreAPI({
			classid: pageInfo.value.classid,
			wallId: pageInfo.value._id,
			userScore: userScore.value
		})
		console.log(res);
		uni.hideLoading()
		if (res.errCode == 0) {
			uni.showToast({
				title: '评分成功',
				icon: 'none'
			})
			// 由于页面不刷新，只能添加假的属性到本地存储
			classList.value[currentIndex.value].userScore = userScore.value
			uni.setStorageSync('classListStorage', classList.value )
			popupScoreClose()
		}
		
	}
	
	function backClassList() {
		uni.navigateBack({
			success() {
				
			},
			fail() {
				uni.reLaunch({
					url: '/pages/index/index'
				})
			}
		})
	}
	
	// 从本地存储取出所有图片的数组
	let classList = ref([])
	classList.value = uni.getStorageSync('classListStorage')
	// console.log(classList.value);
	 classList.value = classList.value.map(item => {
		return {
			...item,
			picurl: item.smallPicurl.replace('_small.webp', '.jpg')
		}
	})
	
	// 通过寻找id相同，获取对应的index
	const currentIndex = ref(null)
	
	// 壁纸信息
	// 定义ts
	const pageInfo = ref<pageInfo>({
		_id: '',
		nickname: '',
		description: '',
		score: '',
		tabs: [],
		classid: '',
		userScore: 0,
		picurl: ''
	})
	let currentId;
	onLoad(async (e) => {
		// console.log(e.id);
		currentId = e.id
		// 适配分享预览页
		if (e.share) {
			const res = await detailWallAPI({id: e.id})
			// console.log(res);
			classList.value = res.data.map(item => {
				return {
					...item,
					picurl: item.smallPicurl.replace('_small.webp', '.jpg')
				}
			})
		}
		// 通过寻找id相同，获取对应的index
		currentIndex.value = classList.value.findIndex(item => {
			return item._id === e.id
		})
		
		// 获取壁纸信息
		pageInfo.value = classList.value[currentIndex.value]
		// 收集已经看过图片的索引值
		imgIndexPush()
	})
	
	// current 改变时会触发  
	function currentChange(e: any) {
		// console.log(e);
		currentIndex.value = e.detail.current
		// 获取壁纸信息
		pageInfo.value = classList.value[currentIndex.value]
		
		// 收集已经看过图片的索引值
		imgIndexPush()
	}
	
	
	// 解决图片加载消耗问题
	const readImgs = ref([])
	
	// 点击下载
	async function downLoad() {
		// #ifdef H5
		uni.showModal({
			content: '请长按保存壁纸',
			showCancel: false
		})
		// #endif
		
		// #ifndef H5
		try{
			uni.showLoading({
				title: '下载中...',
				mask: true
			})
			
			
			uni.getImageInfo({
				src: pageInfo.value.picurl,
				success(res) {
					console.log(res);
					uni.saveImageToPhotosAlbum({
						filePath: res.path,
						async success(res) {
							console.log(res);
							console.log(8888);
							const result = await writeDownLoadAPI({
								classid: pageInfo.value.classid,
								wallId: pageInfo.value._id
							})
							console.log(result);
							if (result.errCode != 0) throw result
							
							uni.showToast({
								title: '下载成功',
								icon: 'none'
							})
						},
						fail(err) { // 拒绝保存，会走fail 
							// console.log(err);
							if (err.errMsg === 'saveImageToPhotosAlbum:fail cancel') {
								uni.showToast({
									title: '保存失败，请重新点击下载',
									icon: 'none'
								})
								return
							}
							// #ifdef APP
								uni.showToast({
									title: '请重新下载之后授权',
									icon: 'none'
								})
							// #endif
							// #ifndef APP
							uni.showModal({
								title: '提示',
								content: '需要授权保存相册',
								success(res) {
									// console.log(res);
									if (res.confirm) { 
										// console.log('确认授权');
										uni.openSetting({
											success(setting) {
												console.log(setting);
												if (setting.authSetting['scope.writePhotosAlbum']) {
													uni.showToast({
														title: '获取授权成功',
														icon: 'none'
													})
												} else {
													uni.showToast({
														title: '获取授权失败',
														icon: 'none'
													})
												}
												// 适配抖音小程序
												// #ifdef MP-TOUTIAO
												if (setting.authSetting['scope.album']) {
													uni.showToast({
														title: '获取授权成功',
														icon: 'none'
													})
												} else {
													uni.showToast({
														title: '获取授权失败',
														icon: 'none'
													})
												}
												// #endif
											}
											
											
										})
									}
								}
							})
							// #endif
							
						},
						complete() {
							uni.hideLoading()
						}
					})  
				}
			})
		}catch(err) {
			console.log(err);
			uni.hideLoading()
		}
		
		// #endif
	}
	function imgIndexPush() {
		readImgs.value.push(
		currentIndex.value <= 0 ? classList.value.length - 1 : currentIndex.value - 1,
		currentIndex.value,
		currentIndex.value >= 11 ? 0 : currentIndex.value + 1
		)
		readImgs.value = [...new Set(readImgs.value)]
	}
	
	// 分享给好友
	onShareAppMessage((e) => {
		return {
			title: `岁月壁纸`,
			// 此分享用到本地数据库，分享给别人没有缓存，加一个参数share判断
			path: `/pages/preview/preview?id=${currentId}&type=share` ,
		}
	})
	
	// 分享朋友圈
	onShareAppMessage((e) => {
		return {
			title: `岁月壁纸`,
			// 不需要携带前面的路径
			query: `id=${currentId}&type=share`
		}
	})
	
	
</script>


<template>
	<view class="preview" v-if="pageInfo">
		<swiper circular :current="currentIndex" @change="currentChange">
			<swiper-item v-for="item,index in classList" :key="item._id">
				<image v-if="readImgs.includes(index)" @click="modelChange" :src="item.picurl" :key="item._id" mode="widthFix"></image>
			</swiper-item>
		</swiper>
		<view class="model" v-show="modelState">
			<!-- #ifndef MP-TOUTIAO -->
			<view @click="backClassList" class="goBack" :style="{top: statusBarHeight + 'px'}">
				<uni-icons type="back" color="#fff" size="20"></uni-icons>
			</view>
			<!-- #endif -->
			
			<view class="count">
				{{currentIndex + 1}} / {{classList.length}}
			</view>
			<view class="time">
				<uni-dateformat :date="new Date()" format="hh:mm"></uni-dateformat>
			</view>
			<view class="date">
				<uni-dateformat :date="new Date()" format="MM月dd日"></uni-dateformat>
			</view>
			<view class="footer">
				<view class="box" @click="clickInfo">
					<uni-icons type="info" size="23"></uni-icons>
					<text>信息</text>
				</view>
				<view class="box" @click="clickscore">
					<uni-icons type="star" size="23"></uni-icons>
					<text>{{pageInfo.score}}分</text>
				</view>
				<view class="box" @click="downLoad">
					<uni-icons type="download" size="23"></uni-icons>
					<text>下载</text>
				</view>
			</view>
		</view>
		<!-- 弹出层 -->
		<uni-popup :safe-area="false" ref="popupInfo" type="bottom" border-radius="10px 10px 0 0">
			<view class="infoPopup">
				<view class="popHeader">
					<view></view>
					<view class="title">
						壁纸信息
					</view>
					<view class="close" @click="popupClose">
						<uni-icons type="closeempty" size="18" color="#999"></uni-icons>	
					</view>
				</view>
				<scroll-view scroll-y="true">
					<view class="content">
						<view class="row">
							<view class="label">
								壁纸ID：
							</view>
							<text class="value" :user-select="true">{{pageInfo._id}}</text>
						</view>
						<view class="row">
							<view class="label">
								发布者：
							</view>
							<text class="value" :user-select="true">{{pageInfo.nickname}}</text>
						</view>
						<view class="row">
							<view class="label">
								评分：
							</view>
							<view class="value rateBox" :selectable="true">
								<uni-rate readonly="true" :value="pageInfo.score"/>
								<text class="score">{{pageInfo.score}}分</text>
							</view>
						</view>
						<view class="row">
							<view class="label">
								摘要：
							</view>
							<text class="value" :user-select="true">{{pageInfo.description}}</text>
						</view>
						<view class="row">
							<view class="label">
								标签：
							</view>
							<view class="value tabs">
								<view class="tab" v-for="item,index in pageInfo.tabs" :key="index">{{item}}</view>
							</view>
						</view> 
						<view class="copyright">
							 声明：本图片来用户投稿，非商业使用，用于免费学习交流，如侵犯了您的权益，您可以拷贝壁纸ID举报至平台，邮箱513894357@qq.com，管理将删除侵权壁纸，维护您的权益。 
						</view>
						<view class="safe-area-inset-bottom">
							
						</view>
					</view>
				</scroll-view>
			</view>
		</uni-popup>
		<!-- 评分 -->
		<uni-popup :is-mask-click="false" ref="popupScore">
			<view class="scorePopup">
				<view class="popHeader">
					<view></view>
					<view class="title">
						{{isScore ? '评分过了~' : '壁纸评分'}}
					</view>
					<view class="close" @click="popupScoreClose">
						<uni-icons type="closeempty" size="18" color="#999"></uni-icons>	
					</view>
				</view>
				<view class="content">
					<uni-rate :disabled="isScore" disabled-color="#ffca3e" v-model="userScore" allowHalf touchable/>
					<text class="text">{{userScore}}分</text>   
				</view>
				<view class="footer">
					<button @click="submitScore" :disabled="!userScore || isScore" plain size="mini">确认评分</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>


<style scoped lang='scss'>
	.preview{
		position: relative;
		swiper{
			height: 100vh;
			swiper-item{
				height: 100%;
				image{
					width: 100%;
					height: 100%;
				}
			}
		}
		
		.model{
			color: #fff;
			&>view{
				position: absolute;
				left: 0;
				right: 0;
				margin: auto;
				width: fit-content;
			}
			.goBack{
				width: 38px;
				height: 38px;
				top: 0;
				left: 30rpx;
				text-align: center;
				line-height: 38px;
				margin-left: 0;
				background-color: rgba(0, 0, 0, .5);
				backdrop-filter: blur(10rpx);
				border-radius: 100px;
			}
			.count{
				top: 10vh;
				background: rgba(0, 0, 0, .3);
				font-size: 26rpx;
				border-radius: 40rpx;
				padding: 8rpx 28rpx;
				color: #fff;
				backdrop-filter: blur(10rpx);
			}
			.time{
				top: calc(10vh + 80rpx);
				font-size: 110rpx;
				line-height: 1em;
				text-shadow: 0 4rpx rgba(0, 0, 0, .3);
			}
			.date{
				top: calc(10vh + 220rpx);
				text-shadow: 0 2rpx rgba(0, 0, 0, .3);
			}
			.footer{
				display: flex;
				justify-content: space-around;
				align-items: center;
				width: 60vw;
				bottom: 10vh;
				height: 120rpx;
				border-radius: 120rpx;
				background-color: rgba(255, 255, 255, .8);
				box-shadow: 0 2rpx 0 rgba(0, 0, 0, .3);
				backdrop-filter: blur(20rpx);
				.box{
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;
					padding: 2rpx 12rpx;
					text{
						margin-top: 3rpx;
						color: $text-font-color-2;
						font-size: 26rpx;
					}
				}
			}
		}
		/* 公共样式 */
		.popHeader{
			display: flex;
			justify-content: space-between;
			.title{
				color: $text-font-color-2;
				font-size: 26rpx;
			}
			.close{
				padding: 6rpx;
			}
		}
		
		.infoPopup{
			background-color: #fff;
			padding: 30rpx;
			border-radius: 30rpx 30rpx 0 0;
			
			scroll-view{
				max-height: 60vh;
				.row{
					display: flex;
					padding: 16rpx 0;
					line-height: 1.7em; 
					.label{
						width: 140rpx;
						color: $text-font-color-3;
						font-size: 30rpx;
						text-align: right;
					}
					.value{
						flex: 1;
						.score{
							padding-left: 10rpx;
							font-size: 26rpx;
							color: $text-font-color-2;
						}
					}
					.rateBox{
						display: flex;
						align-items: center;
					}
					.tabs{
						display: flex;
						flex-wrap: wrap; 
						.tab{
							border: 1px solid $brand-theme-color;
							color: $brand-theme-color;
							padding: 10rpx 30rpx;
							border-radius: 40rpx;
							margin: 0 10rpx 10rpx 0;
							font-size: 22rpx;
							line-height: 1em;
						}
					}
				}
				.copyright{
					font-size: 28rpx;
					padding: 20rpx;
					background-color: #f6f6f6;
					color: #666;
					border-radius: 10rpx;
					margin: 20rpx 0;
					line-height: 1.6em;
				}
			}
		}
		
		.scorePopup{
			width: 70vw;
			border-radius: 30rpx;
			padding: 30rpx;
			background-color: #fff;
			 .content{
				display: flex;
				justify-content: center;
				align-items: center;
				padding: 30rpx 0;
				.text{
					width: 80rpx;
					text-align: right;
				 	font-size: 28rpx;
					color: #FFCA3E;
					padding-left: 10rpx;
				}
			 }
			 .footer{
				 display: flex;
				 justify-content: center;
				 align-items: center;
				 padding: 10rpx 0;
			 }
		}
	}
</style>
 